import {
  Controller,
  Get,
  Post,
  Body,
  ValidationPipe,
  Inject,
  CACHE_MANAGER,
  HttpException,
  HttpStatus,
  Res,
} from '@nestjs/common';
import { RegisterService } from './register.service';
import { RegisterDto } from './dto/register.dto';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
import { HttpReslut } from 'src/common/result/http-reslut';
import { Mailman, MailMessage } from '@squareboat/nest-mailman';
import { Cache } from 'cache-manager';
import { randomCode } from 'src/utils/random';
import { SendEmailCodeDto } from './dto/sendEmailCode.dto';

@ApiTags('注册')
@Controller('/reg')
export class RegisterController {
  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    private readonly registerService: RegisterService,
  ) {}

  @ApiOperation({
    summary: '发送验证码',
  })
  @Post('/sendEmailCode')
  async sendEmail(@Body(new ValidationPipe()) body: SendEmailCodeDto) {
    const code = randomCode();
    const user = { data: code };
    const mail = MailMessage.init()
      .subject('邮箱验证注册码')
      .view('eMail', user);
    Mailman.init()
      .to([body.eMail])
      .send(mail)
      .then(() => {})
      .catch((e) => {
        console.log(e);
      });
    await this.cacheManager.set('eMailCode', code, 60000);
    return new HttpReslut<boolean>(true);
  }

  @ApiOperation({
    summary: '用户注册',
  })
  @ApiBody({ description: '请填写添加内容', type: RegisterDto })
  @Post('/register')
  async create(
    @Body(new ValidationPipe()) createUserDto: RegisterDto,
  ): Promise<HttpReslut<boolean>> {
    const code = await this.cacheManager.get('eMailCode');
    if (!code || code != createUserDto.code) {
      throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST);
    }
    await this.registerService.create(createUserDto);
    return new HttpReslut<boolean>(true);
  }
}
